import React, { useEffect } from 'react';
import { Card, Descriptions, Table, Tag, Alert, Spin, Space } from 'antd';
import type { FormInstance } from 'antd/es/form';
import { useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from '../../store';
import { previewRule } from '../../store/slices/ruleSlice';

interface RulePreviewStepProps {
  form: FormInstance;
}

const RulePreviewStep: React.FC<RulePreviewStepProps> = ({ form }) => {
  const dispatch = useDispatch<AppDispatch>();
  const { rulePreview, loading } = useSelector((state: RootState) => state.rule);

  useEffect(() => {
    const formValues = form.getFieldsValue();
    if (formValues.tables && formValues.tables.length > 0) {
      // 预览规则配置
      const previewData = {
        basicInfo: formValues.basicInfo,
        tables: formValues.tables,
        joins: formValues.joins,
        conditions: formValues.conditions,
        groupBy: formValues.groupBy,
        aggregates: formValues.aggregates,
      };
      dispatch(previewRule(previewData));
    }
  }, [dispatch, form]);

  const getStatusColor = (status: string) => {
    return status === 'active' ? 'green' : 'red';
  };

  const getStatusText = (status: string) => {
    return status === 'active' ? '启用' : '禁用';
  };

  const getOperatorText = (operator: string) => {
    const operatorMap: Record<string, string> = {
      '=': '等于',
      '!=': '不等于',
      '>': '大于',
      '>=': '大于等于',
      '<': '小于',
      '<=': '小于等于',
      'LIKE': '包含',
      'NOT LIKE': '不包含',
      'IN': '在列表中',
      'NOT IN': '不在列表中',
      'BETWEEN': '在范围内',
    };
    return operatorMap[operator] || operator;
  };

  const getAggregateText = (func: string) => {
    const aggregateMap: Record<string, string> = {
      'COUNT': '计数',
      'SUM': '求和',
      'AVG': '平均值',
      'MAX': '最大值',
      'MIN': '最小值',
      'COUNT_DISTINCT': '去重计数',
    };
    return aggregateMap[func] || func;
  };

  const basicInfo = form.getFieldValue('basicInfo');
  const tables = form.getFieldValue('tables') || [];
  const conditions = form.getFieldValue('conditions') || [];
  const aggregates = form.getFieldValue('aggregates') || [];

  return (
    <div>
      <Spin spinning={loading}>
        <Space direction="vertical" style={{ width: '100%' }} size="large">
          <Card title="基本信息" size="small">
            <Descriptions column={2}>
              <Descriptions.Item label="规则名称">
                {basicInfo?.name}
              </Descriptions.Item>
              <Descriptions.Item label="规则状态">
                <Tag color={getStatusColor(basicInfo?.status)}>
                  {getStatusText(basicInfo?.status)}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="规则描述" span={2}>
                {basicInfo?.description || '暂无描述'}
              </Descriptions.Item>
            </Descriptions>
          </Card>

          <Card title="数据表" size="small">
            {tables.length > 0 ? (
              <Table
                dataSource={tables.map((table: string) => ({ tableName: table }))}
                columns={[
                  {
                    title: '表名',
                    dataIndex: 'tableName',
                    key: 'tableName',
                  },
                  {
                    title: '状态',
                    dataIndex: 'status',
                    key: 'status',
                    render: () => <Tag color="green">已选择</Tag>,
                  },
                ]}
                rowKey="tableName"
                pagination={false}
                size="small"
              />
            ) : (
              <Alert message="未选择任何数据表" type="warning" />
            )}
          </Card>

          <Card title="筛选条件" size="small">
            {conditions.length > 0 ? (
              <Table
                dataSource={conditions}
                columns={[
                  {
                    title: '序号',
                    key: 'index',
                    width: 60,
                    render: (_: any, __: any, index: number) => index + 1,
                  },
                  {
                    title: '数据表',
                    dataIndex: 'tableName',
                    key: 'tableName',
                  },
                  {
                    title: '字段',
                    dataIndex: 'fieldName',
                    key: 'fieldName',
                  },
                  {
                    title: '操作符',
                    dataIndex: 'operator',
                    key: 'operator',
                    render: (operator: string) => getOperatorText(operator),
                  },
                  {
                    title: '值',
                    dataIndex: 'value',
                    key: 'value',
                  },
                  {
                    title: '逻辑',
                    dataIndex: 'logic',
                    key: 'logic',
                    render: (logic: string) => (
                      <Tag color={logic === 'AND' ? 'blue' : 'orange'}>
                        {logic === 'AND' ? '并且' : '或者'}
                      </Tag>
                    ),
                  },
                ]}
                rowKey="id"
                pagination={false}
                size="small"
              />
            ) : (
              <Alert message="未设置任何筛选条件" type="info" />
            )}
          </Card>

          <Card title="聚合函数" size="small">
            {aggregates.length > 0 ? (
              <Table
                dataSource={aggregates}
                columns={[
                  {
                    title: '序号',
                    key: 'index',
                    width: 60,
                    render: (_: any, __: any, index: number) => index + 1,
                  },
                  {
                    title: '函数',
                    dataIndex: 'function',
                    key: 'function',
                    render: (func: string) => getAggregateText(func),
                  },
                  {
                    title: '数据表',
                    dataIndex: 'tableName',
                    key: 'tableName',
                  },
                  {
                    title: '字段',
                    dataIndex: 'fieldName',
                    key: 'fieldName',
                  },
                  {
                    title: '别名',
                    dataIndex: 'alias',
                    key: 'alias',
                  },
                ]}
                rowKey="id"
                pagination={false}
                size="small"
              />
            ) : (
              <Alert message="未设置任何聚合函数" type="warning" />
            )}
          </Card>

          {rulePreview && (
            <Card title="预览结果" size="small">
              <Descriptions column={2}>
                <Descriptions.Item label="预估行数">
                  {rulePreview.estimatedRows}
                </Descriptions.Item>
                <Descriptions.Item label="预估时间">
                  {rulePreview.estimatedTime}ms
                </Descriptions.Item>
              </Descriptions>
              
              {rulePreview.sampleData && rulePreview.sampleData.length > 0 && (
                <div style={{ marginTop: 16 }}>
                  <h4>样例数据：</h4>
                  <Table
                    dataSource={rulePreview.sampleData}
                    columns={Object.keys(rulePreview.sampleData[0]).map(key => ({
                      title: key,
                      dataIndex: key,
                      key: key,
                    }))}
                    rowKey={(_record, index) => index || 0}
                    pagination={false}
                    size="small"
                    scroll={{ x: 'max-content' }}
                  />
                </div>
              )}

              {rulePreview.sqlPreview && (
                <div style={{ marginTop: 16 }}>
                  <h4>SQL预览：</h4>
                  <pre style={{ 
                    backgroundColor: '#f5f5f5', 
                    padding: 16, 
                    borderRadius: 4,
                    overflow: 'auto',
                    maxHeight: 200,
                  }}>
                    {rulePreview.sqlPreview}
                  </pre>
                </div>
              )}
            </Card>
          )}
        </Space>
      </Spin>
    </div>
  );
};

export default RulePreviewStep;